package uni_oss

import (
	"autoclave/utils/tools"
	"encoding/json"
	"errors"
	"fmt"
	"golang.org/x/sync/errgroup"
	"net/url"
	"path"
	"sort"
	"strings"
)

const apiExist = "http://192.168.1.196:8889/oss/fileExist"
const apiMove = "http://192.168.1.196:8889/oss/moveFile"
const apiDelete = "http://192.168.1.196:8889/oss/deleteFile"
const apiUpload = "http://192.168.1.196:8889/oss/upload"

type Response struct {
	Code    int
	Message string
	Data    string
}

// ObjectExist 文件是否存在
func ObjectExist(key string) (exist bool, err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	param := url.Values{}
	param.Add("file_path", key)
	res, err := tools.HttpPostForm(apiExist, param, map[string]string{})
	//fmt.Println("RES = ", res)
	resp := Response{}
	err = json.Unmarshal([]byte(res), &resp)
	if err != nil {
		return
	}
	exist = resp.Code == 0
	return
}

func ObjectDelete(key string) (err error) {
	if key == "" {
		err = errors.New("key cant be empty")
		return
	}
	param := url.Values{}
	param.Add("file_path", key)
	res, err := tools.HttpPostForm(apiDelete, param, map[string]string{})
	resp := Response{}
	err = json.Unmarshal([]byte(res), &resp)
	return
}

func ObjectMove(key string, destPath string) (newPath string, err error) {
	newPath = path.Join(destPath, getFileName(key))
	if newPath == key {
		return
	}
	param := url.Values{}
	param.Add("from_path", key)
	param.Add("dst_path", newPath)
	res, err := tools.HttpPostForm(apiMove, param, map[string]string{})
	if err != nil {
		return
	}
	//fmt.Println("response ", res)
	resp := Response{}
	err = json.Unmarshal([]byte(res), &resp)
	if resp.Code != 0 {
		err = errors.New(resp.Message)
		return
	}
	return
}

func getFileName(key string) string {
	res := strings.Split(key, "/")
	return res[len(res)-1]
}

func ObjectsExist(keys []string) error {
	if len(keys) == 0 {
		return errors.New("keys cant be empty")
	}
	g := new(errgroup.Group) // 创建等待组（类似sync.WaitGroup）
	for _, key := range keys {
		newKey := key // 注意此处声明新的变量
		// 启动一个goroutine 判断
		g.Go(func() error {
			exist, err := ObjectExist(newKey)
			if err != nil {
				return err
			}
			if !exist {
				return errors.New("文件不存在" + newKey)
			}
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return err
	}
	return nil
}

func ObjectsMove(keys []string, destPath string) (newPaths []string, err error) {
	if len(keys) == 0 {
		err = errors.New("keys cant be empty")
		return
	}
	resChan := make(chan string, len(keys))
	g := new(errgroup.Group) // 创建等待组（类似sync.WaitGroup）
	for _, key := range keys {
		newKey := key
		g.Go(func() error {
			//fmt.Println("newKey = ", newKey)
			newPath, err2 := ObjectMove(newKey, destPath)
			if err2 != nil {
				return err2
			}
			resChan <- newPath
			return nil
		})
	}
	if err = g.Wait(); err != nil {
		return
	}
	close(resChan)
	for val := range resChan {
		newPaths = append(newPaths, val)
	}
	sort.Strings(newPaths)
	return
}

func DeleteOldPics(oldArr []string, newArr []string) {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println("DeleteOldPics: ", err)
		}
	}()
	for _, v1 := range oldArr {
		inArray := false
		for _, v2 := range newArr {
			if v1 == v2 {
				inArray = true
				break
			}
		}
		if inArray == false {
			go ObjectDelete(v1)
		}
	}
}
